package com.hmy.security.security.filter;

import com.alibaba.fastjson2.JSON;
import com.hmy.security.constant.CacheConstant;
import com.hmy.security.security.bean.JwtUser;
import com.hmy.security.util.CacheUtil;
import com.hmy.security.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 拦截请求 根据token鉴权
 * 不需要使用@Component 会导致执行两次 security与mvc各执行一次
 */
@Slf4j
public class TokenFilter extends GenericFilterBean {

    private final CacheUtil cacheUtil;

    public TokenFilter(CacheUtil cacheUtil) {
        this.cacheUtil = cacheUtil;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        String requestRri = httpServletRequest.getRequestURI();

        // 验证 token 是否存在
        JwtUser userDetail = null;
        String authToken = TokenUtil.getToken(httpServletRequest);
        if (authToken == null) {
            filterChain.doFilter(httpServletRequest, servletResponse);
            return;
        }
        String userDetailStr = cacheUtil.get(authToken);
        if (StringUtils.isNotBlank(userDetailStr)) {
            userDetail = JSON.parseObject(userDetailStr, JwtUser.class);
        }

        if (userDetail != null && SecurityContextHolder.getContext().getAuthentication() == null && TokenUtil.validateToken(authToken)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
            if (userDetail != null && userDetail.getUid() != null) {
                String userTokenKey = String.format(CacheConstant.USER_TOKEN_KEY, userDetail.getUid());
                cacheUtil.del(authToken);
                cacheUtil.lRm(userTokenKey, authToken);
            }
        }
        filterChain.doFilter(httpServletRequest, servletResponse);
    }
}
